<template>
  <div id="withdrawals" style="width: 100%; overflow:hidden;">
    <load-more tip="加载数据中..." v-if="!isloading"></load-more>
    <div v-if="isloading">
      <div>
        <group>
          <cell title="可提金额"><span class="text-orange">{{ withdrawalsMoney.all }}</span> 元</cell>
          <div class="vux-x-input weui-cell weui-vcode">
            <div class="weui-cell__hd">
              <label class="weui-label" style="width: 5em;">提现金额</label>
            </div>
            <div class="weui-cell__bd weui-cell__primary">
              <input class="weui-input text-right" @input="keyUp" placeholder="请输入提现金额" v-model="formItem.cash" />
            </div>
            <div class="weui-cell__ft"><span style="margin-left: 0.1rem;">元</span></div>
          </div>
          <cell title="提现手续费"><span>{{ withdrawalsMoney.serviceCharge }}</span> 元</cell>
        </group>
      </div>
      <p class="text-orange f26" style="padding:0.2rem;">备注：提现金额不限，每笔提现手续费{{ withdrawalsMoney.serviceCharge }}元由提支付宝等对应平台收取，建议100以上起提，每周二提现处理。</p>
      <div class="flex select-bank flex-middle" @click="showPopup = true" v-if="banklist.length > 0">
        <div class="bankicon">
          <img :src="bank.icon" alt="">
        </div>
        <div class="flex-auto" style="margin-left: 0.25rem;" v-if="bank.name">
          <p>{{ bank.label }}</p>
          <p>{{ bank.accountNum }}</p>
        </div>
        <div><i class="icon icon-right" style="font-size: .3rem"></i></div>
      </div>
      <div v-else>
        <group>
          <cell title="您还未添加银行卡" value="添加" is-link link="addwithdrawals"></cell>
        </group>
      </div>
      <div style="padding:0.35rem 0.2rem 0.25rem 0.2rem; background: #fff; margin-top: 0.2rem;">
        <div class="vux-1px"><x-input type="password" :max="16" v-model="formItem.pay_pwd" placeholder="请输入交易密码"></x-input></div>
        <div style="margin-top: 0.3rem;">
          <x-button
            type="primary"
            :show-loading="loading"
            :disabled="!formItem.cash || !formItem.bank_id || formItem.pay_pwd.length < 6"
            @click.native="handleTX"
            action-type="button"
          >{{btn}}</x-button>
        </div>
        <p class="noticemsg text-center" style="margin-top: 0.25rem">
          3~5个工作日到帐（双休日和法定节假日除外）
        </p>
      </div>


      <div class="amap-wrapper" :class="{'amap-wrapper-show': showPopup}">
        <div class="header2">
          <div class="goback" @click="showPopup = false"><i class="icon icon-left"></i></div>
          <div class="title">选择提现账户</div>
          <div class="actions"><router-link to="addwithdrawals" class="text-orange"><i class="icon icon-plus1"></i></router-link></div>
        </div>

        <swipeout>
          <swipeout-item
            class="animated"
            transition-mode="follow"
            v-for="(item, index) in banklist"
            :class="[index === delIndex? 'bounceOutDown': '']"
            :key="index">
            <div slot="right-menu" style="background: #fff;">
              <swipeout-button :width="swipeOutWidth" @click.native="handleDelBank(item.id, index)" type="warn">删除</swipeout-button>
            </div>
            <div slot="content" class="flex select-bank flex-middle vux-1px-t" @click="handleSelectBank(index)">
              <div class="bankicon">
                <i class="icon" :class="item.icon" :style="{color: item.color}" style="font-size: 0.65rem"></i>
              </div>
              <div class="flex-auto" style="margin-left: 0.25rem;">
                <p>{{ item.label }}</p>
                <p>{{ item.accountNum }}</p>
              </div>
              <div>
                <i class="icon" :class="[item.isCheck == 1? 'icon-check text-orange': 'icon-quan1']"></i>
              </div>
            </div>
          </swipeout-item>
        </swipeout>
      </div>
    </div>
  </div>
</template>
<script>
import PubHeader from '../components/PubHeader.vue'
import { Cell, Swipeout, SwipeoutItem, SwipeoutButton, LoadMore } from 'vux'
import { keyUp } from '../libs/fn'

export default{
  components: {
    Swipeout,
    SwipeoutItem,
    SwipeoutButton,
    Cell,
    PubHeader,
    LoadMore
  },
  computed: {
    swipeOutWidth() {
      let width = 80
      const u = navigator.userAgent;
      const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      if(isIOS) {
        width *= window.devicePixelRatio
      }
      return width
    },
    subUrl() {
      return this.$route.query.type == 'commission'? $config.host + '/api/Account/brokerage': $config.host + '/api/Account/cash'
    },
    title() {
      return this.$route.query.type == 'commission'? '佣金提现': '余额提现'
    }
  },
  created() {
    this.getData()
    this.getCash()
  },
  data() {
    return {
      isloading: false,
      uid: this.$store.state.userInfo.uid,
      showPopup: false,
      loading: false,
      delIndex: null,
      btn: '确认提现',
      config: $config,
      withdrawalsMoney: {
        all: 0,
        serviceCharge: 3
      },
      formItem: {
        uid: this.$store.state.userInfo.uid,
        client: $config.client_type,
        device: $config.device_type,
        token: this.$store.state.userInfo.token,
        cash: '',
        bank_id: '',
        pay_pwd: '',
        brokerage: ''
      },
      bank: {
        id: '',
        name: '',
        accountNum: '',
        label: ''
      },
      banklist: [],
      t_money: undefined,
      errCount: 0 //密码错误次数，3次弹出取修改密码
    }
  },
  methods: {
    keyUp() {
      if (!this.formItem.cash.match(/^\d*?\.?\d{0,2}?$/)){
        if(this.t_money === undefined){
          this.t_money = '';
        }
        this.formItem.cash = this.t_money;
      } else {
        this.t_money = this.formItem.cash;
      }
    },
    goback() {
      this.$router.push('account')
    },
    getData() {
      this.$http.post($config.host + '/api/Bank/bankList', qs.stringify({
        uid: this.uid,
        client: $config.client_type,
        device: $config.device_type,
        token: this.$store.state.userInfo.token
      })).then((res) => {
        const {code, msg, data} = res.data
        this.isloading = true
        if(code == '1') {
          let bankArr = []
          const bank_list = data.bank_list
          bank_list.forEach((item) => {
            let isCheck = item.status == 2? 1: 0
            if(item.status == 2) {
              this.bank.name = 'bank' + (item.bank_id > 15? 0: item.bank_id)
              this.bank.accountNum = item.bank_id == 1? item.num: '尾号' + item.last_4,
              this.bank.label = item.bankname
              this.bank.id = item.id
              this.formItem.bank_id = item.id
            }
            bankArr.push({
              id: item.id,
              name: 'bank' + (item.bank_id > 15? 0: item.bank_id),
              label: item.bankname,
              accountNum: item.bank_id == 1? item.num: '尾号' + item.last_4,
              isCheck
            })
          })
          for(let i = 0; i<bankArr.length; i++) {
            if($config.bankConfig[bankArr[i].name]) {
              Object.assign(bankArr[i], {
                icon: $config.bankConfig[bankArr[i].name].icon,
                color: $config.bankConfig[bankArr[i].name].color
              })
            }
          }
          this.banklist = bankArr
        } else if (code == '3') {
          this.$vux.toast.text($config.loginErrMsg, 'middle')
          this.$router.push({path: '/logout'})
        } else if (code == '2'){

        } else {
          this.$vux.toast.text(msg, 'middle')
        }
      }).catch(err => {
        this.$vux.toast.text($config.errMsg, 'middle')
      })

    },
    getCash() {
      this.$http.post($config.host + '/api/Account/showCash', qs.stringify({
        uid: this.uid,
        client: $config.client_type,
        device: $config.device_type,
        token: this.$store.state.userInfo.token
      })).then((res) => {
        const { code, msg, data } = res.data
        const type = this.$route.query.type || ''
        if(code == 1 && data) {
          this.withdrawalsMoney = {
            all: type == 'commission'? data.keyongjin: data.ketijine,
            serviceCharge: data.fei
          }
        } else {
          this.$vux.toast.text(msg, 'middle')
        }
      }).catch(err => {
        console.log(err)
        this.$vux.toast.text($config.errMsg, 'middle')
      })
    },
    //删除银行卡
    handleDelBank(id, index) {
      this.$vux.confirm.show({
        title: '<i class="icon icon-gantanhao"></i>',
        content: '您确定要删除吗?',
        confirmText: '删除',
        cancelText: '取消',
        onConfirm: () => {
          this.$vux.loading.show({
            text: '删除中，请勿操作'
          })
          this.$http.post($config.host + '/api/Bank/delBankCard', qs.stringify({
            id,
            uid: this.uid,
            client: $config.client_type,
            device: $config.device_type,
            token: this.$store.state.userInfo.token
          })).then((res) => {
            const {code, msg} = res.data
            if(code == '1') {
              this.delIndex = index
              setTimeout(() => {
                this.banklist.splice(index, 1)
                this.delIndex = null
                if(id == this.bank.id) {
                  if(this.banklist.length > 0) {
                    this.banklist[0].isCheck = 1
                  }
                  this.bank = {
                    id: this.banklist[0].id || '',
                    label: this.banklist[0].label || '',
                    name: this.banklist[0].name || '',
                    accountNum: this.banklist[0].accountNum || ''
                  }
                  this.formItem.bank_id = this.banklist[0].id || ''
                }
              }, 700)
            } else if (code == '3') {
              this.$vux.toast.text($config.loginErrMsg, 'middle')
              this.$router.push({path: '/logout'})
            } else {
              this.$vux.toast.text(msg, 'middle')
            }
            this.$vux.loading.hide()
          }).catch((err) => {
            this.$vux.loading.hide()
            this.$vux.toast.text($config.errMsg, 'middle')
          })
        }
      })

    },
    //选择银行卡
    handleSelectBank(index) {
      for (let i = 0; i < this.banklist.length; i++) {
        if(this.banklist[i].isCheck == 1 && i != index) {
          this.banklist[i].isCheck = 0
          break
        }
      }
      this.banklist[index].isCheck = 1
      this.showPopup = false
      this.formItem.bank_id = this.banklist[index].id
      this.bank = {
        name: this.banklist[index].name,
        accountNum: this.banklist[index].accountNum,
        label: this.banklist[index].label
      }
      this.$http.post($config.host + '/api/Bank/swichCardNum', qs.stringify({
        uid: this.uid,
        client: $config.client_type,
        device: $config.device_type,
        token: this.$store.state.userInfo.token,
        id: this.banklist[index].id
      }))
    },
    //提现
    handleTX() {
      if(!this.formItem.cash || this.formItem.cash < 0) {
        this.$vux.toast.text('请填写提现金额', 'middle')
        return false
      }
      if(parseFloat(this.formItem.cash) > parseFloat(this.withdrawalsMoney.all)) {
        this.$vux.toast.text('可提现余额不足', 'middle')
        return false
      }
      if(!this.formItem.bank_id) {
        this.$vux.toast.text('请选择银行卡', 'middle')
        return false
      }
      if(!this.formItem.pay_pwd || this.formItem.pay_pwd.length < 6 || this.formItem.pay_pwd.length > 16) {
        this.$vux.toast.text('交易密码格式错误', 'middle')
        return false
      }
      const type = this.$route.query.type || ''
      if(type == 'commission'){
        this.formItem.brokerage = this.formItem.cash
      }
      this.loading = true
      this.$http.post(this.subUrl, qs.stringify(this.formItem)).then(res => {
        const {code, msg} = res.data
        if(code == '1') {
          this.$vux.toast.text('提现申请成功', 'middle')
          this.$router.go(-1)
        } else if (code == '3') {
          this.$vux.toast.text($config.loginErrMsg, 'middle')
          this.$router.push({path: '/logout'})
        } else if (code == '998') {
          this.errCount > 2? this.setPayPwd('find'): this.errCount ++
        } else if (code == '5') {
          this.setPayPwd('set')
        }
        if(code != '1') {
          this.$vux.toast.text(msg, 'middle')
        }
        this.loading = false
      }).catch(err => {
        this.loading = false
        this.$vux.toast.text($config.errMsg, 'middle')
      })
    },
    setPayPwd(type) {
      const content = {
        set: '您还没有设置交易密码',
        find: '您可能忘记了交易密码'
      }
      const confirmText = {
        set: '设置交易密码',
        find: '找回交易密码'
      }
      this.$vux.confirm.show({
        title: '<i class="icon icon-gantanhao"></i>',
        content: content[type],
        confirmText: confirmText[type],
        cancelText: '取消',
        onConfirm: () => {
          this.$router.push('setPayPwd')
        }
      })
    }
  }
}
</script>
<style scoped>
.select-bank{
  padding: 0.2rem;
  background: #fff;
}
.bankicon .icon{
  font-size: 0.9rem;
}
</style>
